#!/usr/bin/env python
# coding: utf-8

# In[3]:


import cv2
import numpy as np
import matplotlib.pyplot as plt


# In[21]:


img_a = cv2.imread(r"D:\a.jpg")


# In[23]:


img_b = cv2.imread(r"D:\b.jpg")


# In[25]:


gray_a=cv2.cvtColor(img_a,cv2.COLOR_BGR2GRAY)
gray_b=cv2.cvtColor(img_b,cv2.COLOR_BGR2GRAY)


# In[27]:


sift=cv2.SIFT_create()
kp_a,des_a=sift.detectAndCompute(gray_a,None)
kp_b,des_b=sift.detectAndCompute(gray_b,None)


# In[31]:


FLANN_INDEX_KDTREE=1
index_params=dict(algorithm=FLANN_INDEX_KDTREE,trees=5)
search_params=dict(chechs=50)
flann=cv2.FlannBasedMatcher(index_params,search_params)
matches=flann.knnMatch(des_a,des_b,k=2)


# In[37]:


good_matches=[]
for m,n in matches:
    if m.distance<0.7*n.distance:
        good_matches.append(m)


# In[43]:


matched_keypoints_img=cv2.drawMatches(
    img_a,kp_a,img_b,kp_b,good_matches,
    None,flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS
)


# In[45]:


src_pts=np.float32([kp_b[m.trainIdx].pt for m in good_matches]).reshape(-1,1,2)
dst_pts=np.float32([kp_a[m.queryIdx].pt for m in good_matches]).reshape(-1,1,2)


# In[49]:


H,_=cv2.findHomography(src_pts,dst_pts,cv2.RANSAC,5.0)


# In[51]:


h_a,w_a=img_a.shape[:2]
h_b,w_b=img_b.shape[:2]


# In[55]:


pts=np.float32([[0,0],[0,h_b],[w_b,h_b],[w_b,0]]).reshape(-1,1,2)
dst_corners=cv2.perspectiveTransform(pts,H)


# In[59]:


all_corners=np.concatenate([dst_corners,np.float32([[0,0],[w_a,0],[w_a,h_a],[0,h_a]]).reshape(-1,1,2)],axis=0)
[x_min,y_min]=np.int32(all_corners.min(axis=0).ravel()-0.5)
[x_max,y_max]=np.int32(all_corners.max(axis=0).ravel()+0.5)


# In[61]:


translation_matrix=np.array([[1,0,-x_min],[0,1,-y_min],[0,0,1]],dtype=np.float32)


# In[63]:


fus_img=cv2.warpPerspective(
    img_b,
    translation_matrix @ H,
    (x_max-x_min,y_max-y_min)
)


# In[65]:


fus_img[-y_min:h_a -y_min,-x_min:w_a -x_min]=img_a


# In[69]:


plt.figure(figsize=(20,20))
plt.subplot(1,4,1)
plt.imshow(cv2.cvtColor(img_a,cv2.COLOR_BGR2RGB))
plt.subplot(1,4,2)
plt.imshow(cv2.cvtColor(img_b,cv2.COLOR_BGR2RGB))
plt.subplot(1,4,3)
plt.imshow(cv2.cvtColor(matched_keypoints_img,cv2.COLOR_BGR2RGB))
plt.subplot(1,4,4)
plt.imshow(cv2.cvtColor(fus_img,cv2.COLOR_BGR2RGB))


# In[ ]:




